<template>
  <div v-if="editablePortlet" class="dropdown-box">
    <a-radio-group v-model:value="radioValue" name="radioGroup" button-style="solid" @change="onChange">
      <a-radio-button v-for="(tim, i) in userPortalList" :key="'portletName-' + i" :value="tim.id">
        <span class="radio-button-box">
          <avic-icon :svg="getIcon(tim.id)" />
          <span class="tabs-drop-item-span" :title="tim.portletName">
            {{ tim.portletName }}
          </span>
        </span>
      </a-radio-button>
      <a-button shape="circle" @click="handleOpenModal()">
        <avic-icon svg="PlusOutlined" />
        <!-- 添加首页 -->
      </a-button>
      <a-button type="link" @click="handleSetting(arr)">
        <avic-icon svg="avic-poratl-set" />
        管理视图
      </a-button>
    </a-radio-group>
    <a-modal title="添加" :open="modalVisible" @ok="handleOk" @cancel="handleCancel">
      <a-form>
        <a-form-item :label-col="{ span: 4 }" :wrapper-col="{ span: 19 }" label="首页名称">
          <a-input v-model:value="portalName" :maxlength="200" placeholder="请输入首页名称" />
        </a-form-item>
      </a-form>
    </a-modal>
    <portal-designer-modal
      v-if="showDesignerModal"
      ref="portalDesignRefName"
      :portal-info="portalInfo"
      @closeModal="handeleCloseDesigner"
      @updatePortalList="updatePortalList"
      @reloadData="reloadData"
    />
  </div>
</template>

<script lang="ts" setup>
import { useAppStore } from '@/store/app';
import PortalDesignerModal from '@/components/portal-designer/PortalDesignModal.vue';
import { savePortalInfo, getUserPortal, getPortletContentById } from '@/api/avic/system/PortalApi';
import { settings } from '@/settings';
const appStore = useAppStore();
const { proxy } = getCurrentInstance();
defineProps({
  tabInfo: {
    type: Object,
    default: null
  }
});
const iconList = [
  'avic-home-4-line',
  'avic-calendar-todo-line',
  'avic-stack-fill',
  'avic-server-line',
  'avic-flow-chart',
  'avic-bookmark-3-line',
  'avic-equalizer-line',
  'avic-archive-2-line',
  'avic-bar-chart-box-line',
  'avic-color-filter-line',
  'avic-gallery-view-2',
  'avic-pass-valid-line',
  'avic-pie-chart-line',
  'avic-sound-module-fill'
];
const visible = ref(false); // Dropdown 显隐控制
const modalVisible = ref(false); // 添加首页名称弹窗显隐控制
const radioValue = ref();
const userPortalList = ref([]); // 用户首页配置列表
const arr = ref({}); // 用户首页配置列表
const showDesignerModal = ref(false);
const portalInfo = ref();
const portalName = ref();
const portalDesign = ref();
const editingPortalId = ref();
const editablePortlet = ref(true);
onMounted(() => {
  getPortalList();
  if (typeof settings.editablePortlet !== 'undefined') {
    editablePortlet.value = settings.editablePortlet;
  }
});
const portalDesignId = computed(() => appStore.portalDesign);

/** 用户首页配置列表数据初始化和刷新**/
async function getPortalList(tempPortalId = '') {
  const res = await getUserPortal();
  if (res.code === '200') {
    userPortalList.value = res.data;
  }
  // 系统默认
  radioValue.value = userPortalList.value.find((item) => item.isDefault === '1')?.id;
  portalDesign.value = radioValue.value;
  if (tempPortalId) {
    const editedPortal = userPortalList.value.find((item) => item.id === tempPortalId);
    if (editedPortal) {
      radioValue.value = tempPortalId;
      portalDesign.value = tempPortalId;
    }
    appStore.portalDesign = '';
    nextTick(() => {
      appStore.SET_PORTAL_DESIGN(portalDesign.value);
    });
  }
  // 用户首次登陆系统，需要初始化 或者 删除时需要更新
  else if (!portalDesignId.value) {
    appStore.portalDesign = portalDesign.value;
  } else {
    const userConfigPortal = userPortalList.value.find((item) => item.id === portalDesignId.value);
    if (userConfigPortal) {
      radioValue.value = userConfigPortal.id;
    } else {
      appStore.portalDesign = radioValue.value;
    }
  }
  const userPortal = userPortalList.value.filter((item) => item.id === radioValue.value)[0];
  if (userPortal) {
    arr.value = userPortal;
  } else {
    // 处理没有匹配项的情况，可能是赋值为空数组或者进行其他逻辑处理
    arr.value = {};
  }
}

/** 点击radio设置默认状态**/
function onChange(e) {
  const { value } = e.target;
  const userPortal = userPortalList.value.filter((item) => item.id === value)[0];
  if (userPortal) {
    arr.value = userPortal;
  } else {
    // 处理没有匹配项的情况，可能是赋值为空数组或者进行其他逻辑处理
    arr.value = {};
  }
  radioValue.value = value;
  // 保存个性化配置数据
  portalDesign.value = radioValue.value;
  appStore.SET_PORTAL_DESIGN(portalDesign.value);
}

/** 点击设置打开首页布局设置弹窗 **/
function handleSetting(record) {
  visible.value = false; // 隐藏下拉菜单
  modalVisible.value = false;
  if (typeof record.resourceType === 'undefined' || (Number(record.resourceType) !== 0 && Number(record.resourceType) !== 1)) {
    editingPortalId.value = record.id;
  }
  getPortletContentByIds(record);
}

/** 根据portlet id 获取content内容**/
function getPortletContentByIds(record) {
  if (!record.id) return;
  getPortletContentById(record.id).then((res) => {
    if (res.data) {
      const result = {
        ...res,
        content: JSON.parse(res.data.content),
        ...record
      };
      portalInfo.value = result;
      showDesignerModal.value = true;
    }
  });
}

/** 打开添加弹窗**/
function handleOpenModal() {
  visible.value = false;
  portalName.value = ''; // 清空添加弹窗表单
  modalVisible.value = true;
}

/** 请求接口保存首页名称 **/
function handleOk() {
  if (portalName.value) {
    modalVisible.value = false;
    savePortalInfo({ portletName: portalName.value }).then((res) => {
      if (res.data) {
        modalVisible.value = false;
        const result = {
          id: res.data,
          portletName: portalName.value,
          content: null
        };
        editingPortalId.value = res.data;
        portalInfo.value = result;
        showDesignerModal.value = true;
        getPortalList(); // 保存成功更新列表
        handleSetting(result);
        proxy.$message.success('保存成功');
      }
    });
  }
}

/** 首页弹窗添加取消操作 **/
function handleCancel() {
  modalVisible.value = false;
}

function handeleCloseDesigner() {
  showDesignerModal.value = false;
  editingPortalId.value = '';
}

/** 删除操作更新tabsDropRefName列表 */
function updatePortalList() {
  const tempPortalId = editingPortalId.value;
  getPortalList(tempPortalId);
}
/** 重新加载数据 */
function reloadData() {
  const tempPortalId = editingPortalId.value;
  getPortalList(tempPortalId);
}
/** 图标 */
function getIcon(uuid) {
  if (typeof uuid === 'string' && uuid.length) {
    let sum = 0;
    for (let i = 0; i < uuid.length; i++) {
      sum += uuid.charAt(i).charCodeAt(0);
    }
    const cIndex = sum % iconList.length;
    return iconList[cIndex];
  }
  if (typeof uuid === 'number') {
    return iconList[uuid % iconList.length];
  }
  return iconList[0];
}
</script>

<style lang="less" scoped>
.dropdown-box {
  margin-bottom: 12px;
  margin-left: 4px;
  overflow-x: auto;
  overflow-y: hidden;

  :deep(.ant-radio-group) {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    .ant-radio-button-wrapper {
      padding: 0 20px;
      border-radius: 16px;
      border-color: transparent;
      display: flex;
      align-items: center;
      background-color: #ffffff;

      &:not(:first-child)::before {
        display: none;
      }
      & > span {
        white-space: nowrap;
        text-overflow: ellipsis;
        max-width: 180px;
        display: inline-block;
        overflow: hidden;
        vertical-align: middle;
      }
      .radio-button-box {
        .avic-icon {
          font-size: 1.1em;
          margin-right: 4px;
        }
      }
    }
    .ant-radio-button-wrapper-checked {
      background: @primary-color;
      color: #ffffff;
    }
    .ant-tabs-dropdown-menu {
      :deep(.ant-tabs-dropdown-menu-item > span) {
        span {
          flex: 1 0 0;
          display: inline-flex;
          justify-content: space-between;
        }
      }

      .dropdown-box {
        .ant-dropdown-link {
          padding: 0;
          border-color: transparent;
        }
      }
    }

    .ant-btn-link {
      color: @text-color-secondary;

      &:hover {
        color: @primary-color;
      }

      .svg-icon {
        margin-right: 4px;
        vertical-align: -0.175em;
      }
    }
  }
}
.tabs-drop-item-span {
  white-space: nowrap;
  text-overflow: ellipsis;
  max-width: 120px;
  border: 0;
  display: inline-block;
  overflow: hidden;
  vertical-align: middle;
  line-height: initial;
}
:deep(.radio-button-box) {
  display: flex;
  align-items: center;
}
</style>
